package com.example.yzx.allriddle;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
import com.example.yzx.allriddle.daomain.Jzw;
import com.example.yzx.allriddle.daomain.QApp;
import com.example.yzx.allriddle.utils.Db;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

public class GameActivity extends AppCompatActivity {
    private List<Jzw> list=new ArrayList<>();
    private String[] tlist=new String[10];
    private String[] answerlist=new String[11];
    private TextView tishis;
    private Button last;
    private Button next;
    private Button star;
    static int pagesum=1;
    static int grade=0;
    private TextView ct;
    private TextView titles;
    private EditText edit;
    private QApp app;
    private Db db = new Db(this, 1);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);
        ActionBar actionBar = getSupportActionBar();
        if(actionBar != null){
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        app= (QApp) getApplication();
        ct=findViewById(R.id.ct);
        edit=findViewById(R.id.edit);
        last=findViewById(R.id.last);
        next=findViewById(R.id.next);
        star=findViewById(R.id.star);
        tishis=findViewById(R.id.tishis);
        titles=findViewById(R.id.titles);
        titles.setText("第 "+pagesum+" 题");
        //五次抓取数据
        for(int i=0;i<5;i++) {
            init();
        }

    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish(); // back button
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
    //点击提示
    public  void anview(View view){
        AlertDialog alertDialog2 = new AlertDialog.Builder(this)
                .setTitle("  第一个字为："+(list.get(pagesum-1).getAnsewr().trim()).substring(0,1))//标题
                .create();
        alertDialog2.show();
    }
    //点击上一题
    public void lasts(View view){
        if(pagesum>1) {
            String oj=list.get(pagesum-2).getAnsewr().trim();
            ct.setText(list.get(pagesum-2).getContent()+"  ("+oj.length()+"个字)");
            edit.setHint(tlist[pagesum-2]);
            String edits=edit.getText().toString().trim();
            System.out.println(edits);
            if(!edits.equals(""))
                tlist[pagesum-1]=edits;
            pagesum--;
            titles.setText("第 "+pagesum+" 题");
        }else{
            AlertDialog alertDialog2 = new AlertDialog.Builder(this)
                    .setTitle("到底了")//标题
                    .setMessage(" ")//内容
                    .create();
            alertDialog2.show();
        }
        if(pagesum==9){
            next.setVisibility(View.VISIBLE);
        }
    }
    //点击下一题
    public void nexts(View view){
        if(pagesum==9){
            String oj=list.get(pagesum).getAnsewr().trim();
            ct.setText(list.get(pagesum).getContent()+"  ("+oj.length()+"个字)");
            edit.setHint(tlist[pagesum]);
            String edits=edit.getText().toString();
            System.out.println(edits+"chacahkan");
            if(!edits.equals(""))
                tlist[pagesum-1]=edits;
            edit.setText(null);
            star.setVisibility(View.VISIBLE);
            next.setVisibility(View.INVISIBLE);
        }else if(pagesum==10){
            last.setVisibility(View.INVISIBLE);
            edit.setVisibility(View.INVISIBLE);
            titles.setVisibility(View.INVISIBLE);
            tishis.setVisibility(View.INVISIBLE);
            star.setVisibility(View.INVISIBLE);
            System.out.println(Arrays.toString(tlist));
            String edits=edit.getText().toString();
            System.out.println(edits+"chacahkan");
            for(int z=0;z<10;z++){
                System.out.println(list.get(z).getAnsewr());
                if(list.get(z).getAnsewr().trim().equals(tlist[z])){
                    grade+=10;
                }
            }
            update(grade);
            String answer="";

            for (int j=0;j<list.size();j++){
                answer="第"+(j+1)+"题答案 ："+list.get(j).getAnsewr()+"         ";
                answerlist[j+1]=answer;
            }
            ct.setHeight(900);
            answerlist[0]="  恭喜你完成了测试,你的分数为 ："+grade;
            //设置listview
            if(pagesum==10) {
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.answer, answerlist);
                ListView listView = findViewById(R.id.listview);
                listView.setAdapter(adapter);
            }
        }else{
            String oj=list.get(pagesum).getAnsewr().trim();
            ct.setText(list.get(pagesum).getContent()+"  ("+oj.length()+"个字)");
            edit.setHint(tlist[pagesum]);
            String edits=edit.getText().toString();
            edit.setText(null);
            System.out.println(edits+"chacahkan");
            if(!edits.equals(""))
                tlist[pagesum-1]=edits;
        }
        if(pagesum==1){
            next.setVisibility(View.VISIBLE);
        }
        pagesum++;
        titles.setText("第 "+pagesum+" 题");
    }
    private void init(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Random rand = new Random();
                    int rd=(int)(300*Math.random());
                    OkHttpClient client=new OkHttpClient();
                    String url="https://api.jisuapi.com/jzw/search?appkey=85cdfb160033ed3f&keyword=&pagenum="+rd+"&pagesize=10";
                    Request request=new Request.Builder()
                            .url(url)
                            .build();
                    Response response=client.newCall(request).execute();
                    String data=response.body().string();
                    json(data);
                    System.out.println(list.size());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private void json(String data){
        try {
            JSONObject json = new JSONObject(data);
            JSONObject result = json.getJSONObject("result");
            JSONArray results = result.getJSONArray("list");
            List<Jzw> list2=new ArrayList<>();
            for (int i = 0; i < results.length(); i++) {
                JSONObject value = results.getJSONObject(i);
                String title = value.getString("content");
                String answer = value.getString("answer");
                Jzw jzw=new Jzw(title,answer);
                list2.add(jzw);
            }
            Message message = hand.obtainMessage();
            message.what = 1;
            message.obj = list2;
            hand.sendMessage(message);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    public void update(float x){
        int aid=app.getserid();
        float grades=0;
        SQLiteDatabase sqLiteDbup = db.getReadableDatabase();
        Cursor c = sqLiteDbup.query("user", new String[]{"uid", "name", "word","grade"}, "", null, null, null, null);
        while (c.moveToNext()) {
            Integer id = c.getInt(c.getColumnIndex("uid"));
            float grade = c.getFloat(c.getColumnIndex("grade"));
            if(id==aid){
                grades=grade;
            }
        }
        if(x>grades){
            SQLiteDatabase sqLiteDbups = db.getReadableDatabase();
            ContentValues value = new ContentValues();
            value.put("grade",x);
            sqLiteDbups.update("user",value, "uid="+aid+"", null);
        }
        SQLiteDatabase sqLiteDbups = db.getReadableDatabase();
        Cursor cs = sqLiteDbups.query("user", new String[]{"uid", "name", "word","grade"}, "", null, null, null, null);
        while (cs.moveToNext()) {
            Integer id = cs.getInt(c.getColumnIndex("uid"));
            String name = cs.getString(c.getColumnIndex("name"));
            float grade = cs.getFloat(c.getColumnIndex("grade"));
            System.out.println(grade+"/"+name+"/"+id);
        }
    }
    private Handler hand = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                List<Jzw> lt = ( List<Jzw> ) msg.obj;
                for(int i=0;i<lt.size();i++){
                    list.add(lt.get(i));
                }
                 String oj=list.get(pagesum-1).getAnsewr().trim();
                 ct.setText(list.get(pagesum-1).getContent()+"  ("+oj.length()+"个字)");
            }
        }

    };
}